<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkContact\Action\Dashboard\Traits;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\Utils\Codec\Json;
use MoChat\App\WorkContact\Contract\WorkContactContract;
use MoChat\App\WorkContact\Contract\WorkContactEmployeeContract;
use MoChat\App\WorkContact\Contract\WorkContactTagContract;
use MoChat\App\WorkContact\Contract\WorkContactTagPivotContract;

/**
 * 公共方法-筛选客户.
 * @Controller
 */
trait FilterContactTraits
{
    /**
     * @Inject
     * @var WorkContactEmployeeContract
     */
    protected $workContactEmployeeService;

    /**
     * @Inject
     * @var WorkContactContract
     */
    protected $workContactContract;

    /**
     * @Inject
     * @var WorkContactTagPivotContract
     */
    protected $workContactTagPivotService;

    /**
     * @Inject
     * @var WorkContactTagContract
     */
    protected $workContactTagContract;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    private function filterContact($params): array
    {
//        $this->logger->error("筛选参数".Json::encode($params));
        // 参数处理
        $data = [
            'corpId' => $params['corpId'],
            'employeeIds' => $params['employeeIds'] ?? [], // 员工ids
            'gender' => $params['gender'] ?? '', // 性别：0-未知 1-男性 2-女性
            'tagIds' => $params['tagIds'] ?? [], // 客户标签
            'startTime' => $params['startTime'] ?? '', // 添加时间-开始
            'endTime' => $params['endTime'] ?? '', // 添加时间-结束
            'roomIds' => $params['roomIds'] ?? [], // 客户所在群聊
            'deleteTagIds' => $params['deleteTagIds'] ?? [], // 排除客户标签
            'addWay' => $params['addWay'] ?? '', // 添加客户的来源
        ];
        // 数据兼容（部分接口查询全部为：3）
        if ((int) $data['gender'] === 3) {
            $data['gender'] = '';
        }
        $result = ['total' => 0, 'list' => []];
        if (empty($data['employeeIds'])) {
            return $result;
        }

        // 1、查询员工所有客户-添加时间
        $search = [
            'corpId' => $data['corpId'],
            'employeeIds' => $data['employeeIds'],
            'startTime' => $data['startTime'],
            'endTime' => $data['endTime'],
            'addWay' => $data['addWay'],
            'status' => 1,
        ];
        $contactEmployees = $this->workContactEmployeeService->getWorkContactEmployeesBySearch($search, ['contact_id', 'create_time']);
        if (empty($contactEmployees)) {
            return $result;
        }
        $contactIds = array_unique(array_column($contactEmployees, 'contactId'));
        // 查询已打标签客户
        if (! empty($data['tags'])) {
            $contactsTag = $this->workContactTagPivotService->getWorkContactTagPivotsByContactIdsEmployeeIdsTagIds($contactIds, $data['employeeIds'], $params['tags'], 1, ['contact_id']);
            if (empty($contactsTag)) {
                return $data;
            }
            $contactIds = array_unique(array_column($contactsTag, 'contactId'));
        }

        // 查询客户信息
        if ($data['gender'] === '' || $data['gender'] === null) {
            $list = $this->workContactContract->getWorkContactsById($contactIds, ['id', 'name', 'avatar', 'wx_external_userid']);
        } else {
            $list = $this->workContactContract->getWorkContactsByIdsGender($contactIds, (int) $data['gender'], ['id', 'name', 'avatar', 'wx_external_userid']);
        }

        $contacts = array_column($contactEmployees, null, 'contactId');
        foreach ($list as &$item) {
            $item['avatar'] = file_full_url($item['avatar']);
            $item['createTime'] = $contacts[$item['id']] ? $contacts[$item['id']]['createTime'] : '';
            $item['tags'] = $this->getContactTags($item['id']);
        }
        unset($item);
        return ['total' => count($list), 'list' => $list];
    }

    private function getContactTags($contactId): array
    {
        $contactTags = $this->workContactTagPivotService->getWorkContactTagPivotsByContactId($contactId, ['contact_tag_id']);
        if (empty($contactTags)) {
            return [];
        }
        $tagIds = array_unique(array_column($contactTags, 'contactTagId'));
        $tags = $this->workContactTagContract->getWorkContactTagsById($tagIds, ['name']);
        return empty($tags) ? [] : array_column($tags, 'name');
    }
}
